<?php

namespace app\admin\controller\integral;

use app\admin\model\Admin;
use app\admin\model\Department;
use app\admin\model\finance\extract\Week;
use app\admin\model\integral\Samplebook;
use app\admin\controller\School;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 *
 * @icon fa fa-circle-o
 */
class Taskbook extends Backend
{
    
    /**
     * Bookstore模型对象
     * @var \app\admin\model\integral\Bookstore
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\integral\Taskbook;
        $this->TeacherModel = new \app\admin\model\integral\Teachertel;
        $this->Samplebook = new Samplebook;
        $this->bookstoreModel = new \app\admin\model\integral\Bookstore;
        $this->loadlang('finance.extract.week');
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("adminlist", collection(Admin::where(['department' => Session::get('admin.department')])->select())->toArray());
    }

    /**
     * 查看
     */
    public function index($ids=null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$row) {
                $row->visible(['id','school_id','status','createtime','updatetime']);
            }
            //print_r($this->model->getLastSql());die;
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign('ids',TableField('Task','extract_week',$ids));
        $this->view->assign('task_id',$ids);
        return $this->view->fetch();
    }


    public function add($ids=null,$task_id=null)
    {
        if($this->auth->userid != 1)
        {
            $where['userid'] = $this->auth->userid;
        }
        $where['id'] = $task_id;
        $where['type'] = 2;
        $row = Db::table('hdyj_finance_extract_task')->where($where)->find();
        if(!$row) $this->error('你当前还没有任务!');
        $admin = Session::get('admin');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['week_id'] = $ids;
            $params['task_id'] = $task_id;
            $params['publish'] = $admin['userid'];
            $params['z_publish'] = $admin['userid'];
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    // 启动事务
                    Db::startTrans();
                    try{
                        if(isset($params['evaluation_summary']))
                        {
                            $params['evaluation_summary'] = json_encode($params['evaluation_summary'],true);
                        }else{
                            unset($params['evaluation_summary']);
                        }
                        $result = $this->model->allowField(true)->save($params);
                        //添加老师信息
                        $booskId = $this->model->getLastInsID();
                        $teacher = json_decode($params['teacher'],true);
                        $hezuoshudian = json_decode($params['hezuoshudian'],true);
                        $hezuozhixiaoyuan = json_decode($params['hezuozhixiaoyuan'],true);
                        if($hezuoshudian)
                        {
                            foreach ($hezuoshudian as &$param) {
                                $param['week_id'] = $ids;
                                $param['userid'] = $admin['userid'];
                                $param['books_id'] = $booskId;
                                $param['status'] = '1';
                            }
                            $this->bookstoreModel->allowField(true)->saveAll($hezuoshudian);
                        }
                        if($hezuozhixiaoyuan)
                        {
                            foreach ($hezuozhixiaoyuan as &$param) {
                                $param['week_id'] = $ids;
                                $param['userid'] = $admin['userid'];
                                $param['books_id'] = $booskId;
                                $param['status'] = '2';
                            }
                            $this->bookstoreModel->allowField(true)->saveAll($hezuozhixiaoyuan);
                        }
                        if($teacher)
                        {
                            foreach ($teacher as &$param) {
                                $param['week_id'] = $ids;
                                $param['userid'] = $admin['userid'];
                                $param['books_id'] = $booskId;
                            }
                            $this->TeacherModel->allowField(true)->saveAll($teacher);
                        }
                        //添加样书
                        Samplebook::create([
                            'week_id'=>$ids,
                            'books_id'=>$booskId,
                            'userid'=>$admin['userid'],
                            'yiluntidian'=>$params['yiluntidian'],
                            'yilunjiaoan'=>$params['yilunjiaoan'],
                        ]);
                        // 提交事务
                        Db::commit();
                        $this->success();
                    } catch (\think\exception\PDOException $e) {
                        // 回滚事务
                        Db::rollback();
                        $this->error($this->model->getError());
                    }

                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('week_id',$ids);
        $this->view->assign('admin',$admin);
        return $this->view->fetch();
    }

    /**
     * 添加新的学校
     * @return string
     * @throws \think\Exception
     */
    public function addschool()
    {
        $school = new School();
        $school->add();
        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $admin = Session::get('admin');
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $teacher = $this->TeacherModel->where(['books_id'=>$ids])->field('name,subject,number,tel,id')->select()->toArray();//获取老师信息
        $samplebook  = $this->Samplebook->where(['books_id'=>$ids])->field('yiluntidian,yilunjiaoan')->find();//获取图书信息
        $bookstore = $this->bookstoreModel->where(['books_id'=>$ids])->field('id,bookstore_name,boss,tel,control,discount,status')->select()->toArray();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['z_publish'] = $admin['userid'];
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    //开启事务操作
                    Db::startTrans();
                    try{
                        if(isset($params['evaluation_summary']))
                        {
                            $params['evaluation_summary'] = json_encode($params['evaluation_summary'],true);
                        }
                        $result = $row->allowField(true)->save($params);
                        $teacher = json_decode($params['teacher'],true);
                        $hezuoshudian = json_decode($params['hezuoshudian'],true);
                        $hezuozhixiaoyuan = json_decode($params['hezuozhixiaoyuan'],true);
                        $hezuoshudianupdate = [];
                        $hezuoshudianinset = [];
                        if($hezuoshudian)
                        {
                            foreach ($hezuoshudian as &$param) {
                                if(!isset($param['id']))
                                {
                                    $param['userid'] = $admin['userid'];
                                    $param['books_id'] = $ids;
                                    $param['week_id'] = $row['week_id'];
                                    $param['status'] = '1';
                                    $hezuoshudianinset[] = $param;
                                }else{
                                    $param['userid'] = $admin['userid'];
                                    $hezuoshudianupdate[] = $param;
                                }
                            }
                            if($hezuoshudianupdate)
                            {
                                $this->bookstoreModel->saveAll($hezuoshudianupdate);//联通方式更新新的数据
                            }
                            if($hezuoshudianinset)
                            {
                                $this->bookstoreModel->allowField(true)->saveAll($hezuoshudianinset);
                            }
                        }
                        $hezuozhixiaoyuanupdate = [];
                        $hezuozhixiaoyuaninstall = [];
                        if($hezuozhixiaoyuan)
                        {
                            foreach ($hezuozhixiaoyuan as &$param) {
                                if(!isset($param['id']))
                                {
                                    $param['userid'] = $admin['userid'];
                                    $param['books_id'] = $ids;
                                    $param['week_id'] = $row['week_id'];
                                    $param['status'] = '2';
                                    $hezuozhixiaoyuaninstall[] = $param;
                                }else{
                                    $param['books_id'] = $ids;
                                    $hezuozhixiaoyuanupdate[] = $param;
                                }
                            }
                            if($hezuozhixiaoyuanupdate)
                            {
                                $this->bookstoreModel->saveAll($hezuozhixiaoyuanupdate);//联通方式更新新的数据
                            }
                            if($hezuozhixiaoyuaninstall)
                            {
                                $this->bookstoreModel->allowField(true)->saveAll($hezuozhixiaoyuaninstall);
                            }

                        }
                        $update = [];
                        $inser = [];
                        if($teacher)
                        {
                            foreach ($teacher as $param) {
                                if(!isset($param['id']))
                                {
                                    $param['week_id'] = $row['week_id'];
                                    $param['userid'] = $admin['userid'];
                                    $param['books_id'] = $ids;
                                    $inser[] = $param;
                                }else{
                                    $param['userid'] = $admin['userid'];
                                    $param['books_id'] = $ids;
                                    $update[] = $param;
                                }
                            }
                        }
                        if($update)
                        {
                            $this->TeacherModel->saveAll($update);//联通方式更新新的数据
                        }
                        if($inser)
                        {
                            $this->TeacherModel->allowField(true)->saveAll($inser);//联通方式插入新的数据
                        }
                        $this->Samplebook->allowField(true)->save($params,['books_id'=>$ids]);//样书数据修改
                        // 提交事务
                        Db::commit();
                        $this->success();
                    } catch (\think\exception\PDOException $e) {
                        // 回滚事务
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if($samplebook)
        {
            $samplebook['yiluntidian'] = json_decode($samplebook['yiluntidian'],true);
            $samplebook['yilunjiaoan'] = json_decode($samplebook['yilunjiaoan'],true);
        }
        if($row['evaluation_summary'])
        {
            $row['evaluation_summary'] = json_decode($row['evaluation_summary'],true);
        }
        $this->view->assign("row", $row);
        $this->view->assign("teacher", $teacher);
        $this->view->assign("samplebook", $samplebook);
        $this->view->assign("bookstore", $bookstore);
        $this->view->assign("admin", $admin);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            //删除老师数据， 图书科目
            $samplebooklist = $this->Samplebook->where('books_id', 'in', $ids)->select();
            $teacherlist = $this->TeacherModel->where('books_id', 'in', $ids)->select();
            $bookstorelist = $this->bookstoreModel->where('books_id', 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            foreach ($samplebooklist as $k => $v) {
                $count += $v->delete();
            }
            foreach ($teacherlist as $k => $v) {
                $count += $v->delete();
            }
            foreach ($bookstorelist as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
